import { getQueryObject } from 'party_fe_component/src/utils';
import { initEnviorment } from 'party_fe_component';
import changeThemeColor from './changeThemeColor'
import apiServerMap from '../../config/serverMap'
import fg from 'flaginfojssdk'

fg._NO_SDK_THEME = true // v1.x 不再重复加载elemet-ui的样式

export default function initLogin(apiServerMap) {
    return new Promise((resolve, reject) => {
        // 获取token|theme|type|pid，后面会适配载体
        try {
            var queryObj = getQueryObject()
            if (top === self) {
                initEnv(queryObj)
                resolve(queryObj) // for debug
            } else {
                fg.ready(function (loginInfo) {
                    const appInfo = {
                        ...(loginInfo.userInfo || {}),
                        token: loginInfo.token || queryObj.token,
                        theme: loginInfo.theme || queryObj.theme || 'default',
                        businessType: loginInfo.businessType || queryObj.businessType,
                        spId: loginInfo.spId || queryObj.spId,
                        moduleId: loginInfo.moduleId || queryObj.moduleId,
                        appId: loginInfo.appId || queryObj.appId,
                        color: loginInfo.color || queryObj.color,
                    }
                    initEnv(appInfo)
                    resolve(appInfo)
                }).catch((e) => {
                    console.error(e)
                })
            }
        } catch (e) {
            reject(e)
        }
    })
}

function initEnv(appInfo) {
    const apiConfig = {
        // apiServerMap需包含 {common, org}
        apiServerMap,
        goLogin() {
            fg.loginOut()
        }
    }
    // 全局只需调用一次。渲染前初始化，避免组件内请求发起时还没有设置apiServer
    initEnviorment(appInfo, apiConfig)
    //替换主题色
    changeThemeColor(appInfo.color || '#ed4040')
}
